var table;
$(function() {
	$("#userList_queryDiv").bind("keydown",function(e){
		// 兼容FF和IE和Opera
		var theEvent = e || window.event;
		var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
		if (code == 13) {
			//回车执行查询
			$("#serach").click();
		}
	});

	table = $('#userList_dataList').dataTable({
		"fnServerData" : function(sSource, aoData, fnCallback) {
			$.ajax({
				"dataType" : 'json',
				"type" : "POST",
				"url" : ctx + "/mgr/sysUserManager/ajaxList",
				"data" : {
					"currentResult" : aoData.start,
					"showCount" : aoData.length,
					"draw":aoData.draw,
					"login" : $("#login").val(),
					"name" : $("#name").val(),
					"phone" : $("#phone").val(),
					"state" : $("#state").val(),
					"type" : $("#type").val()
				},
				"success" : fnCallback
			});
		},
		"aoColumns": [
            {"data": null},
			{"data": "login"},
			{"data": "name"},
			{"data": "phone"},
            {"data": "email"},
			{"data": "type"},
            {"data": "state"},
			{"data": "uptime"},
			{"data": null}
		],
		"fnRowCallback":function(nRow, aData, iDisplayIndex){
            $('td:eq(0)', nRow).html( iDisplayIndex + 1 );
			$('td:eq(5)', nRow).html(getUserType(aData));
			$('td:eq(6)', nRow).html(getUserState(aData));
            $('td:eq(7)', nRow).html(DateFormatHandle(aData));
			$('td:eq(8)', nRow).html(getUserOperate(aData));
		}
	});

	/**
	 * 搜索
	 */
	$('#userList_serach').click(function() {
		table.fnDraw();
	});
});


/**
 * 时间格式处理
 * @param data 时间
 * @constructor
 */
function DateFormatHandle(data) {
	var upDateTime = new Date(parseInt(data.uptime));
	return formatDateTool(upDateTime);
}

/**
 *用户类型判断
 * @param data 返回JSON
 * @returns {string} 用户类型
 */
function getUserType(data) {
    var str = '';
    if(data.type == null || data.type == "" || data.type =="0"){
        str += "系统用户";
    }else if(data.type == 1){
        str += "商户";
    }else if(data.type == 9){
        str += "超级管理员";
	}else{
        str += "未知";
    }
    return str;
}

/**
 * 用户状态处理
 * @param data 相应JSON
 * @returns {string} 返回状态
 */
function getUserState(data) {
    var str = '';
    if(data.state == null || data.state == "" ||  data.state=="0"){
        str += "正常";
    }else if(data.state == 1){
        str += "删除";
    }else if(data.state == 2){
        str += "锁定";
    }else{
        str += "未知";
    }
    return str;
}


function getUserOperate(data) {
    var str = '';
	if(data.type !== "9"){
        str += '<button onclick="getUserInfo(\'' + data.userId + '\',\'query\')" class="btn btn-primary btn-xs">编辑</button>&nbsp;&nbsp;';
        if(data.state == 0 ){
            str += '<button onclick="setUserState(\'' + data.userId + '\', \'1\')" class="btn btn-primary btn-xs">删除</button>&nbsp;&nbsp;';
        }else{
            str += '<button onclick="setUserState(\'' + data.userId + '\', \'0\')" class="btn btn-primary btn-xs">启用</button>&nbsp;&nbsp;';
        }
	}
	return str;
}




/**
 * 用户状态操作
 * @param userId 用户ID
 * @state state 用户状态
 */
function setUserState(userId, state){
	if (!window.confirm("确认该操作吗?")) {
		return;
	}
	$.ajax({
		url: ctx + "/mgr/sysUserManager/setUserState",
		type: 'post',
		dataType: 'json',
		"data": {
			"userId" : userId,
			"state" : state
		},
		timeout: ajaxTimeout,
		error: function (json) {
			toastr.error("操作失败," + json.errorMSG)
		},
		success: function (json) {
			if (json.isSuccess=="0") {
				toastr.success("设置成功")
			} else {
				toastr.error(json.errorMSG)
			}
			table.fnPageChange(getPageNum(table, false));
		}
	});
}

/**
 * 用户信息编辑查看
 * @param userId 用户ID
 */
function getUserInfo(userId) {
	var url = ctx + "/mgr/sysUserManager/userEditInfo?userId=" + userId;
	window.location.href = url;
}

function add0(m){return m<10?'0'+m:m }
function formatDateTool(curTime)
{
    // curTime是整数，否则要parseInt转换
    var time = new Date(curTime);
    var y = time.getUTCFullYear();
    var m = time.getUTCMonth()+1;
    var d = time.getUTCDate();
    var h = time.getUTCHours();
    var mm = time.getUTCMinutes();
    var s = time.getUTCSeconds();
    return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
}